package com.lzhl.buildjar.util;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 李柱良(@柱子的日月)
 * @date 2016/3/21
 */
public class StringUtils {

    public static List<String> toList(String str) {
        List<String> lines = new LinkedList<String>();
        if(str == null || str.length() == 0) {
            return lines;
        }

        ByteArrayInputStream is = null;
        BufferedReader reader = null;
        try {
            is = new ByteArrayInputStream(str.getBytes());
            reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
//                if(line.length() > 0) {
                    lines.add(line);
//                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return lines;
    }

    public static String toString(List<String> lines) {
        String str = "";
        if(lines == null || lines.size() == 0) {
            return str;
        }

        ByteArrayOutputStream os = null;
        PrintWriter writer = null;

        try {
            os = new ByteArrayOutputStream();
            writer = new PrintWriter(os);

            for(String line : lines) {
                if(line != null) {
                    line = line.trim();
//                    if(line.length() > 0) {
                        writer.println(line);
//                    }
                }
            }

            writer.flush();
            str = os.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (writer != null) {
                writer.close();
            }

            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException ignore) {
            }
        }

        return str;
    }

    public static boolean equals(String str1, String str2) {
        if(str1 == null) {
            str1 = "";
        }
        if(str2 == null) {
            str2 = "";
        }

        return str1.equals(str2);
    }

    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }

    public static String trim(String str) {
        if(str == null) {
            return "";
        }
        return str.trim();
    }

}
